package com.meisen.springboot.service.impl;

import com.meisen.springboot.entity.User;
import com.meisen.springboot.repo.UserRepository;
import com.meisen.springboot.service.UserService;
import com.meisen.springboot.service.redis.UserRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;


/**
 * 用户服务接口实现
 * @author meisen
 * 2018-04-18
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final UserRedisService userRedisService;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, UserRedisService userRedisService) {
        this.userRepository = userRepository;
        this.userRedisService = userRedisService;
    }


    @Override
    public User findUserById(String id) {
        Optional<User> optionalUser = Optional.ofNullable(userRedisService.get(id));
        return optionalUser.orElseGet(() -> userRepository.findById(id).orElseGet(() -> new User(User.NO_SUCH_USER, "")));
    }

    @Override
    public User findUserByUsername(String username) {
        Optional<User> optionalUser = Optional.ofNullable(userRedisService.get(username));
        return optionalUser.orElseGet(() -> userRepository.findByUsername(username).orElseGet(() -> new User(User.NO_SUCH_USER, "")));
    }


    @Override
    public User registerUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User saveOrUpdateUser(User user) {
        User resultUser = userRepository.save(user);
        userRedisService.put(resultUser.getUid(), resultUser, 3600L);
        userRedisService.put(resultUser.getUsername(), resultUser, 3600L);
        return resultUser;
    }

    @Override
    public void removeUser(String id) {
        userRepository.deleteById(id);
        User user = userRedisService.get(id);
        userRedisService.remove(user.getUsername());
        userRedisService.remove(user.getUid());
    }

    @Override
    public List<User> findAll() {
        return (List<User>) userRepository.findAll();
    }
}
